using System.Collections;
using System.Collections.Generic;
using UnityEngine;

namespace 前置知识
{
    public class MapGenerate : MonoBehaviour
    {
        public int width = 20;
        public int height = 20;
        public float lacunarity = 0.1f;
        public float tileHeightMultiplier = 1f;
        public GameObject tilePrefab;
        public Material[] tileMaterials;

        public int randomSeed = 0;

        /// <summary>
        /// 生成地图
        /// </summary>
        public void GenerateMap()
        {
            Random.InitState(randomSeed);
            Debug.Log("random222:" + Random.value);
            Debug.Log("random333:" + Random.value);
            Debug.Log("random:" + Random.value);

            for (int i = 0; i < width; i++)
            {
                for (int j = 0; j < height; j++)
                {
                    var tile = Instantiate(tilePrefab, transform);
                    float y = Mathf.PerlinNoise(i * lacunarity, j * lacunarity) * tileHeightMultiplier;

                    tile.transform.position = new Vector3(i, y, j);

                    if (y < 0.3f * tileHeightMultiplier)
                    {
                        tile.gameObject.GetComponent<MeshRenderer>().material = tileMaterials[0];
                    }
                    else if (y < 0.7f * tileHeightMultiplier)
                    {
                        tile.gameObject.GetComponent<MeshRenderer>().material = tileMaterials[1];
                    }
                    else
                    {
                        tile.gameObject.GetComponent<MeshRenderer>().material = tileMaterials[2];
                    }
                }
            }
        }

        public void CleanMap()
        {
            for (int i = transform.childCount - 1; i >= 0; i--)
            {
                DestroyImmediate(transform.GetChild(i).gameObject);
            }
        }
    }
}